package com.talent.codes.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

import com.talent.cloud.core.web.BaseFilter;
import com.talent.cloud.web.constant.SecurityConstants;
import com.talent.cloud.web.helper.UserInfoHelper;
import com.talent.cloud.web.model.UserInfo;

public class LocalAdminFilter extends BaseFilter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request instanceof HttpServletRequest){
            String ctx = ((HttpServletRequest) request).getContextPath();
            if(ctx==null || "/".equals(ctx)) ctx = "";
            String ip = request.getRemoteAddr();
            String uri = ((HttpServletRequest) request).getRequestURI();
            String adminPath = ctx + "/"; //admin
            UserInfo ui = null;
            try{
                ui = UserInfoHelper.getUserInfo(request);
            }catch (Throwable tr){
                ui = null;
            }

            if(ui == null) {
                if (uri.startsWith(adminPath)) {
                    if (ui == null) {
                        //if (IpUtil.checkLocalIP4(ip)) {
                        if ("127.0.0.1".equals(ip)) {
                            ui = new UserInfo();
                            ui.setUserId("localhost");
                            ui.setUserName("CMD后台用户");
                            ui.setUserType(SecurityConstants.USER_SCOPE_INNER);
                            ui.setUserScope(SecurityConstants.USER_SCOPE_INNER);
                            ui.setStatus("S");
                            ui.setLoginIp(ip);
                            request.setAttribute(SecurityConstants.USER_PRINCIPAL,ui);
                        }
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}
